//
//  AddIncomeViewController.m
//  Wallets Manager
//
//  Created by Tung Nguyen on 9/26/12.
//  Copyright (c) 2012 BKHN. All rights reserved.
//

#import "AddIncomeViewController.h"
#import "DataBaseAccess.h"

@interface AddIncomeViewController ()
{
    NSDate *currentDate;
}
@end

@implementation AddIncomeViewController
@synthesize incomeNameTextField;
@synthesize categoryLabel;
@synthesize categoryTextField;
@synthesize categoryImageView;
@synthesize amountTextField;
@synthesize dateTextField;
@synthesize planTextField;
@synthesize planImageView;
@synthesize addButton;
@synthesize noteTextField;
@synthesize monthViewCalendar;
@synthesize pickerViewPopup;
@synthesize walletNameTextField;
@synthesize dateString;
@synthesize headerTextField;
@synthesize kindOfView;
@synthesize currentIncome;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    //---------------------Init Current Image Name If User don't select category
    currentImageStr = @"category.png";
    
    folyAppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    walletNameTextField.text = delegate.currentWallet.w_name;
    
    currentIncomeType = [DataBaseAccess iTypeForName:@"Other"];
    currentPlan       =  [DataBaseAccess planForName:@"Chưa có kế hoạch" andWallet:delegate.currentWallet];
    currentPlan.p_image = @"category.png";
    
    //-----------------Set form to edit if from Edit---------------
    if([kindOfView isEqualToString:@"Edit"]) {
        
        headerTextField.text = @"Edit Income";
        [addButton setTitle:@"Edit" forState:UIControlStateNormal];
        incomeNameTextField.text = currentIncome.i_name;
        categoryTextField.text = currentIncome.iToIncomeType.it_name;
        [categoryImageView setImage:[UIImage imageNamed:currentIncome.iToIncomeType.it_image]];
        amountTextField.text = [NSString stringWithFormat:@"%d",[currentIncome.i_amount integerValue]];
        
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
        [dateFormatter setDateFormat:@"MM/dd/yyyy"];
        dateTextField.text = [dateFormatter stringFromDate:currentIncome.i_date];
        currentDate = currentIncome.i_date;
        currentPlan = currentIncome.iToPlan;
        currentIncomeType = currentIncome.iToIncomeType;
        
        planTextField.text = currentIncome.iToPlan.p_name;
        [planImageView setImage:[UIImage imageNamed:currentIncome.iToPlan.p_image]];
        
        noteTextField.text = currentIncome.i_notes;
    }
    
    // Do any additional setup after loading the view from its nib.
    //----------------------NSNotification Center-------------------------//
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getCategoryOnSuccess:) name:@"getCategoryOnSuccess" object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getPlanOnSuccess: ) name:@"getPlanFromIncomeViewOnSuccess" object:nil];
    
//    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardDidShow :) name:UIKeyboardDidShowNotification object:nil];
}

- (void)viewDidUnload
{
    [self setIncomeNameTextField:nil];
    [self setCategoryLabel:nil];
    [self setAmountTextField:nil];
    [self setDateTextField:nil];
    [self setPlanTextField:nil];
    [self setNoteTextField:nil];
    [self setCategoryImageView:nil];
    [self setCategoryTextField:nil];
    [self setWalletNameTextField:nil];
    [self setPlanImageView:nil];
    [self setAddButton:nil];
    [self setHeaderTextField:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (IBAction)backButtonPressed:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - IBAction Delegate

- (IBAction)addButtonPressed:(id)sender {
    folyAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    double walletBalance = [delegate.currentWallet.w_balance doubleValue];
    double amountInput = [amountTextField.text doubleValue];
    if( [kindOfView isEqualToString:@"Add"]){
        if ( ([incomeNameTextField.text isEqualToString:@""] ||
              [amountTextField.text isEqualToString:@""] ||
              [dateTextField.text isEqualToString:@""] ) ) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Warning" message:@"Incompleted adding!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
            [incomeNameTextField resignFirstResponder];
            [amountTextField resignFirstResponder];
        } else if (amountInput <= 0) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Warning" message:@"Invalid value of money!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
            [amountTextField setText:nil];
            [incomeNameTextField resignFirstResponder];
            [amountTextField resignFirstResponder];
        } else {
            currentPlan.p_startamount  = [NSNumber numberWithInt:[currentPlan.p_startamount intValue] + [amountTextField.text intValue]];
            if(![currentPlan.p_name isEqualToString:@"Chưa có kế hoạch"]){
                if([currentPlan.p_startamount integerValue] >= [currentPlan.p_amount integerValue]) {
                    currentPlan.p_completed = [NSNumber numberWithBool:YES];
                    [[NSNotificationCenter defaultCenter]postNotificationName:@"planCompleted" object:currentPlan.p_name];
                }
            }
               
            NSLog(@"Add : startamount%d amount :%d ",[currentPlan.p_startamount integerValue],[currentPlan.p_amount integerValue]);
            delegate.currentWallet.w_balance = [NSNumber numberWithDouble:(walletBalance + amountInput)];
            [DataBaseAccess createIncomeWithname:incomeNameTextField.text andAmount:amountInput andDate:currentDate andNotes:noteTextField.text inPlan:currentPlan ofType:currentIncomeType];
            [[NSNotificationCenter defaultCenter]postNotificationName:@"reloadIncomeExpenseTable" object:nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"incomeAdded" object:incomeNameTextField.text];
            [self.navigationController popViewControllerAnimated:YES];
        }
    } else {
        if ( ([incomeNameTextField.text isEqualToString:@""] ||
              [amountTextField.text isEqualToString:@""] ||
              [dateTextField.text isEqualToString:@""] ) ) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Warning" message:@"Incompleted editing!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
            [incomeNameTextField resignFirstResponder];
            [amountTextField resignFirstResponder];
        } else if ([amountTextField.text doubleValue] <= 0) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Warning" message:@"Invalid value of money!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
            [amountTextField setText:nil];
            [incomeNameTextField resignFirstResponder];
            [amountTextField resignFirstResponder];
        } else {
            
            double firstAmount = [currentIncome.i_amount doubleValue];
        
            if ( (walletBalance - (firstAmount - amountInput)) < 0) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Warning" message:@"Your wallet is not enough money!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                [alert show];
                [amountTextField setText:nil];
                [incomeNameTextField resignFirstResponder];
                [amountTextField resignFirstResponder];
            } else {
                
                currentIncome.i_name = incomeNameTextField.text;
                currentIncome.iToIncomeType = currentIncomeType;
                currentIncome.i_amount = [NSNumber numberWithDouble:amountInput];
        
                NSLog(@"Add : startamount%0.2f amount :%0.2f ",[currentPlan.p_startamount doubleValue],[currentPlan.p_amount doubleValue]);

                if(![currentPlan.p_name isEqualToString:@"Chưa có kế hoạch"]) {
            
                    currentPlan.p_startamount = [NSNumber numberWithDouble:[currentPlan.p_startamount doubleValue] + amountInput - firstAmount];
            
                    if([currentPlan.p_startamount doubleValue] >= [currentPlan.p_amount doubleValue]) {
                        currentPlan.p_completed = [NSNumber numberWithBool:YES];
                        [[NSNotificationCenter defaultCenter]postNotificationName:@"planCompleted" object:currentPlan.p_name];
                    }else {
                        currentPlan.p_completed = [NSNumber numberWithBool:NO];
                    }
                }

                currentIncome.i_date = currentDate;
                currentIncome.iToPlan= currentPlan;
                currentIncome.i_notes = noteTextField.text;
                delegate.currentWallet.w_balance = [NSNumber numberWithDouble:(walletBalance - (firstAmount - amountInput))];
                [DataBaseAccess saveData];
                [[NSNotificationCenter defaultCenter]postNotificationName:@"reloadIncomeExpenseTable" object:nil];
                [self.navigationController popViewControllerAnimated:YES];
            }
        }
    }
}

#pragma mark - Touch Delegate
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    
    UITouch *touch = [touches anyObject];
    CGPoint touchPosition = [touch locationInView:touch.view];
    
    if (touchPosition.y >=101 && touchPosition.y <=141) {
        
        SelectIncomeCategory *selectIncomCategory = [[SelectIncomeCategory alloc]init];
        [self.navigationController pushViewController:selectIncomCategory animated:YES];
        
    } else if ( (touchPosition.y >= 274) && (touchPosition.y <= 314) ) {
        
        SelectPlanViewController *selectPlanViewController = [[SelectPlanViewController alloc]init];
        selectPlanViewController.isFromView = @"Add Income";
        [self.navigationController pushViewController:selectPlanViewController animated:YES];
        
    }
}

#pragma mark - Text Field Delegate
-(void) textFieldDidBeginEditing:(UITextField *)textField {
    if(textField == amountTextField) {
        [self addButtonToKeyboard];
    } else {
        //doneButton.hidden = YES;
    }
    
    if( textField == dateTextField) {
        [self createDatePickerView];
    }
}

//-(void) textFieldDidEndEditing:(UITextField *)textField {
//    [self.view endEditing:YES];
//    [textField resignFirstResponder];
//   
//}
-(BOOL) textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    activeTextField = nil;
    return YES;
}

#pragma mark - Month Calendar
- (void) createDatePickerView {
    
    if(pickerViewPopup == nil)
    {
        pickerViewPopup = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];
        
        [pickerViewPopup setActionSheetStyle:UIActionSheetStyleBlackTranslucent];
        
        //    datePickerView = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 44, 0, 0)];
        //    datePickerView.datePickerMode = UIDatePickerModeDate;
        //    datePickerView.hidden = NO;
        //    datePickerView.date = [NSDate date];
        //    [datePickerView addTarget:self action:@selector(datePickerValueChanged :) forControlEvents:UIControlEventValueChanged];
        
        UIToolbar *pickerToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
        pickerToolbar.barStyle = UIBarStyleBlackOpaque;
        [pickerToolbar sizeToFit];
        
        NSMutableArray *barItems = [[NSMutableArray alloc] init];
        
        UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneDateButtonPressed:)];
        [barItems addObject:doneBtn];
        
        UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
        [barItems addObject:flexSpace];
        
        UIBarButtonItem *cancelBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelDateButtonPressed:)];
        [barItems addObject:cancelBtn];
        
        [pickerToolbar setItems:barItems animated:YES];
        
        if(monthViewCalendar == nil)
        {
            monthViewCalendar = [[TKCalendarMonthView alloc] initWithSundayAsFirst:NO];
            monthViewCalendar.delegate  = self;
            monthViewCalendar.dataSource = self;
            //NSLog(@"MONTH %f x %f", monthViewCalendar.bounds.size.width, monthViewCalendar.bounds.size.height);
            [monthViewCalendar reload];
        }
        [monthViewCalendar setFrame:CGRectMake(0, 44, 320, monthViewCalendar.bounds.size.height)];
        pickerViewPopup.clipsToBounds=YES;
        
        //[pickerViewPopup addSubview:datePickerView];
        
        [pickerViewPopup addSubview:pickerToolbar];
        [pickerViewPopup addSubview:monthViewCalendar];
        [pickerViewPopup setBounds:CGRectMake(0, 0, 320, 460)];
        [pickerViewPopup showInView:self.view];
        [self popUpRefreshFrame];
        
        //[self popUpRefreshFrame];
        
    }else
    {
        [pickerViewPopup showInView:self.view];
        [self popUpRefreshFrame];
    }
    
}

-(void)popUpRefreshFrame
{
    [UIView beginAnimations:@"resize_animation" context:NULL];
    [UIView setAnimationDuration:0.3];
    
    pickerViewPopup.clipsToBounds=YES;
    [pickerViewPopup setFrame:CGRectMake(0.0, 460 - monthViewCalendar.bounds.size.height - 44, 320, monthViewCalendar.bounds.size.height + 44)];
    
    [UIView commitAnimations];
    
    
}

- (NSArray*) calendarMonthView:(TKCalendarMonthView*)monthView marksFromDate:(NSDate*)startDate toDate:(NSDate*)lastDate{
	return nil;
}

-(void)calendarMonthView:(TKCalendarMonthView *)monthView didSelectDate:(NSDate *)date
{
    NSLog(@"aaaaa%@", date);
    currentDate = date;
}

- (void) calendarMonthView:(TKCalendarMonthView*)monthView monthDidChange:(NSDate*)month animated:(BOOL)animated
{
    //NSLog(@"FRAME = %f X %f", monthView.frame.size.width , monthView.frame.size.height);
    [self performSelector:@selector(popUpRefreshFrame)];
}

-(void)doneDateButtonPressed:(id)sender{
    //Do something here here with the value selected using [pickerView date] to get that value
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"MM/dd/yyyy"];
    
    dateString = [dateFormatter stringFromDate:currentDate];
    [dateTextField setText:dateString];
    [dateTextField resignFirstResponder];
    [pickerViewPopup dismissWithClickedButtonIndex:1 animated:YES];
}

-(void)cancelDateButtonPressed:(id)sender{
    
    //    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    //    [dateFormatter setDateFormat:@"MM/dd/yyyy"];
    //    [dateTextField setText:[dateFormatter stringFromDate:datePickerView.date]];
    [dateTextField resignFirstResponder];
    [pickerViewPopup dismissWithClickedButtonIndex:1 animated:YES];
    //[currencyPickerViewPopup dismissWithClickedButtonIndex:1 animated:YES];
}

#pragma mark - Notification Center 
-(void) getCategoryOnSuccess : (NSNotification*) notification {
    NSDictionary *tempDict = [notification object];
    currentIncomeType = [tempDict objectForKey:@"key"];
    currentImageStr = currentIncomeType.it_image;
    [categoryImageView setImage:[UIImage imageNamed:currentImageStr]];
    categoryTextField.text = currentIncomeType.it_name;
}

-(void)getPlanOnSuccess: (NSNotification *)notification {
    NSDictionary *tempDict = [notification object];
    currentPlan = [tempDict objectForKey:@"key"];
    [planImageView setImage:[UIImage imageNamed:currentPlan.p_image]];
    planTextField.text = currentPlan.p_name;
}

//- (void)keyboardDidShow:(NSNotification *)note {
//    // create custom button
//    if(!isDoneShouldHidden) {
//        doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
//        doneButton.frame = CGRectMake(0, 163, 106, 53);
//        doneButton.adjustsImageWhenHighlighted = NO;
//        [doneButton setImage:[UIImage imageNamed:@"DoneUp.png"] forState:UIControlStateNormal];
//        [doneButton setImage:[UIImage imageNamed:@"DoneDown.png"] forState:UIControlStateHighlighted];
//        [doneButton addTarget:self action:@selector(doneButton:) forControlEvents:UIControlEventTouchUpInside];
//        
//        // locate keyboard view
//        UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
//        UIView* keyboard = nil;
//        for(int i=0; i<[tempWindow.subviews count]; i++) {
//            keyboard = [tempWindow.subviews objectAtIndex:i];
//            // keyboard found, add the button
//            if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) {
//                if([[keyboard description] hasPrefix:@"<UIPeripheralHost"] == YES)
//                    [keyboard addSubview:doneButton];
//                
//            } else {
//                if([[keyboard description] hasPrefix:@"<UIKeyboard"] == YES)
//                    [keyboard addSubview:doneButton];
//                
//            }
//        }
//
//    }
// 
//}
//
//- (void)doneButton:(id)sender {
//    NSLog(@"Input: %@", amountTextField.text);
//    [amountTextField resignFirstResponder];
//}
- (id)getKeyboardWindow {
	UIWindow *windowTemp = nil;
	for (UIWindow *w in [[UIApplication sharedApplication] windows]) {
		if ([NSStringFromClass([w class]) isEqualToString:@"UITextEffectsWindow"]) {
			windowTemp = w;
			break;
		}
	}
	return windowTemp;
}

- (void)addButtonToKeyboard {
    // create custom button
   // if (doneButton == nil) {
//      buttonDone  = [UIButton buttonWithType:UIButtonTypeCustom];
//        buttonDone.frame = CGRectMake(0, 163, 106, 53);
//        [buttonDone setImage:[UIImage imageNamed:@"DoneUp.png"] forState:UIControlStateNormal];
////    }
////    else {
////        [doneButton setHidden:NO];
////    }
//    
//    [buttonDone addTarget:self action:@selector(doneButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    // locate keyboard view
//    UIWindow *tempWindow;
//    for (UIWindow *w in [[UIApplication sharedApplication] windows]) {
//		if ([NSStringFromClass([w class]) isEqualToString:@"UITextEffectsWindow"]) {
//            tempWindow = w;
//			break;
//		}
//	}
    
    id windowTemp = [self getKeyboardWindow];
	
	// Если нужное окно найдено
	if (windowTemp) {
		
		// Пробуем удалить кнопку (мы ее могли создать раньше, в этом или другом UITextField)
		for (UIView *v in [windowTemp subviews]) {
			if ([v isKindOfClass:[UIButton class]]) {
				[v setHidden:FALSE];
				buttonDone = (UIButton *)v ;
				[buttonDone removeTarget:nil action:NULL forControlEvents:UIControlEventAllEvents];
			}
		}
		
		// Создаем кнопку если она еще не создана
		if (!buttonDone) {
			UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
			[button setAdjustsImageWhenHighlighted:NO];
			[[button titleLabel] setLineBreakMode:UILineBreakModeWordWrap];
			[[button titleLabel] setNumberOfLines:0];
			[[button titleLabel] setTextAlignment:UITextAlignmentCenter];
        
			[windowTemp addSubview:button];
			
			buttonDone = button;
		}

    [buttonDone addTarget:self action:@selector(actionKeyboardHide:) forControlEvents:UIControlEventTouchUpInside];
    }
}

- (void)actionKeyboardHide:(UIButton *)sender {
	[self resignFirstResponder];
//	if (self.delegate && [self.delegate respondsToSelector:@selector(textFieldShouldReturn:)])
//		[self.delegate performSelector:@selector(textFieldShouldReturn:) withObject:self];
}

//- (void)doneButtonClicked:(id)Sender {
//    [amountTextField resignFirstResponder];
//    //Write your code whatever you want to do on done button tap
//    //Removing keyboard or something else
//}




@end
